// spacePopoverSel 为空间切换混入
const app = getApp()
let spacePopoverSel = require('../behaviors/space/space-popover-sel.js')
import {
  reqDeviceByImei,
  reqAlarmReceiverList,
  reqDeviceAdd,
  reqReceiverSpaceAdd,
  reqOrgList,
  reqAlarmReceiverBySpaceId
} from '../../../../request/api'
import {
  showMsg
} from '../../../../utils/config';
Page({
  behaviors: [spacePopoverSel], //空间弹窗选择混入
  data: {
    navHeight: app.globalData.navHeight + 'px', //头部距离
    bottomHeight: app.globalData.bottomHeight + 'px', //iphone底部距离
    rolename: '',
    imeiList: [{
      id: 0,
      imei: '',
      type: ''
    }],

    // 接警人开始
    showPeopleCall: false,
    alarmReceiverList: [],
    alarmPage: 1,
    alarmIsNextPage: true,
    alarmReceiverArr: [], //最终提交值id集合
    selAlarmReceiverArr: [], //展示渲染页面
    alarmReceiverIdList1: [],
    alarmReceiverIdList2: [],
    alarmReceiverIdList3: [],
    alarmReceiverIdList4: [],

    expanded: true,
    level: 1,
    levelList: [{
        value: 1,
        name: "一级",
      },
      {
        value: 2,
        name: "二级",
      },
      {
        value: 3,
        name: "三级",
      },
      {
        value: 4,
        name: "四级",
      },
    ],
    // 接警人结束
    form: {
      orgName: "",
      orgId: "",
    },
    showUnitSelection: false, //是否展示单位选择弹窗
    apporgId: "", //==1为全部单位
    showorg: false,
    orgList: [],
  },
  onLoad(e) {
    this.setData({
      rolename: app.globalData.rolename
    })
    this.getItemInfo(e)
  },
  onShow() {
    this.setData({
      apporgId: app.globalData.orgId
    })
    // this.getOrgList()
    // 初始状态
    this.setData({
      alarmReceiverList: [],
      alarmIsNextPage: true,
      alarmPage: 1
    })
    this.getSpaceList() //更新安装点列表
    // if(app.globalData.orgId==1) return;
    this.getAlarmReceiverList() //获取接警人列表
  },
  // 获取信息
  getItemInfo(e) {
    let info = JSON.parse(e.info)
    let {
      spaceId,
      spaceName
    } = info
    if (spaceId) {
      this.setData({
        spaceId,
        spaceName
      })
    }
  },


  // 点击新增一条设备输入框
  clickAddDevice() {
    let {
      imeiList
    } = this.data
    if (imeiList.length >= 5) return showMsg("一次最多安装5台设备")
    let id = imeiList[imeiList.length - 1].id + 1
    imeiList.push({
      id,
      imei: '',
      type: ''
    })
    this.setData({
      imeiList
    })
  },
  // 删除一条设备输入框
  clickDecreaseImei(e) {
    let {
      id
    } = e.target.dataset
    let {
      imeiList
    } = this.data
    imeiList.splice(id, 1)
    imeiList.forEach((item, index) => {
      item.id = index
    })
    this.setData({
      imeiList
    })
  },
  // 判断imei是否已存在
  async getDeviceByImei(id, imei) {
    let {
      imeiList
    } = this.data
    const res = await reqDeviceByImei(imei)
    if (res.code === 12020 || res.code === 12021) {
      // 清空操作
      // imeiList.forEach(item => {
      //     if (item.id === id) {
      //         item.imei = ''
      //         item.type = ''
      //     }
      // })
      imeiList.forEach(item => {
        if (item.id === id) {
          item.imei = imei
          // item.type = res.data.row.productName
        }
      })
      this.setData({
        imeiList
      })
      showMsg(res.message)
      return
    }
    if (res.code !== 20000) return showMsg(res.message)
    imeiList.forEach(item => {
      if (item.id === id) {
        item.imei = imei
        item.type = res.data.row.productName
      }
    })
    this.setData({
      imeiList
    })
  },
  // 获取设备imei
  imeiChange(e) {
    let {
      id
    } = e.target.dataset
    let {
      value
    } = e.detail
    if (value.length >= 3) {
      this.getDeviceByImei(id, value)
    }
    if (value.length <= 0) {
      // 删除到没有时，清除imei和类型
      let {
        imeiList
      } = this.data
      imeiList.forEach(item => {
        if (item.id === id) {
          item.imei = ''
          item.type = ''
        }
      })
      this.setData({
        imeiList
      })
    }
  },
  // js判断字符串是否为JSON格式
  isjson(str) {
    if (typeof str == 'string') {
      try {
        var obj = JSON.parse(str);
        if (typeof obj == 'object' && obj) {
          return true;
        } else {
          return false;
        }

      } catch (e) {
        console.log('error：' + str + '!!!' + e);
        return false;
      }
    }
    console.log('It is not a string!')
  },
  /**
   * @name:  扫码imei
   * @msg: 掉接口时记得询问清楚截取方法
   * @return {*}
   */
  imeiScan(e) {
    let that = this
    let {
      id
    } = e.target.dataset
    let qrcode = ''
    wx.scanCode({
      success(res) {
        console.log(res);
        qrcode = res.result;
        if (!qrcode) return showMsg('扫描失败，请重新扫描')
        if (qrcode.length >= 3) {
          // let reg = /^\d+$/.test(qrcode)
          // if (reg) {
          //     qrcode = qrcode.substring(0, 3);
          //     that.getDeviceByImei(id, qrcode)
          // } else {
          //     qrcode = qrcode.substr(qrcode.indexOf(86), 3)
          //     that.getDeviceByImei(id, qrcode)
          // }
          if (that.isjson(qrcode)) {
            const result = JSON.parse(qrcode);
            // JSON字符格式
            that.setData({
              searchValue: result.ID, //威视达康摄像机取值，后续看需求更改 lc
            })
            that.getDeviceByImei(id, result.ID)
          } else {
            // 非JSON格式
            if (qrcode.startsWith("V380^")) {
              //宏视
              let  parts = qrcode.split('^')
              let id_part ='9673960'+ parts[1] 
              that.setData({
                searchValue: id_part,
              })
              that.getDeviceByImei(id, id_part)
            }else{
              that.setData({
                searchValue: qrcode,
              })
              that.getDeviceByImei(id, qrcode)
            }
          }
        } else {
          showMsg('扫描失败，请重新扫描')
          return
        }
      }
    })
  },
  // 扫码后赋值imei
  imeiScanChange(id, code) {
    let {
      imeiList
    } = this.data
    imeiList.forEach(item => {
      if (item.id === id) {
        item.imei = code
      }
    })
    this.setData({
      imeiList
    })
  },
  // 清除imei
  imeiClear(e) {
    let {
      id
    } = e.target.dataset
    let {
      imeiList
    } = this.data
    imeiList.forEach(item => {
      if (item.id === id) {
        item.imei = ''
        item.type = ''
      }
    })
    this.setData({
      imeiList
    })
  },

  //展开/收缩接警人
  togglePanel() {
    this.setData({
      expanded: !this.data.expanded
    });
  },

  // 点击展示接警人弹窗
  clickShowPeopleCall(e) {
    if (!this.data.form.orgId) return showMsg("请先选择单位")
    if (!this.data.spaceName) return showMsg("请先选择安装点")
    console.log('selAlarmReceiverArr', this.data.selAlarmReceiverArr);

    this.closePeopleCall() // 点击关闭接警人弹窗
    let list = this.data.alarmReceiverList.map(item => {
      item.disabled = false;
      this.data.selAlarmReceiverArr.forEach(item2 => {
        if (item.id == item2.id) {
          console.log('==item2', item2);
          item.disabled = true;

          const checkbox = this.selectComponent(`.checkboxes-${item2.id}`);
          checkbox.toggle();
        }
      })
      return item
    })
    this.setData({
      showPeopleCall: true,
      // valueInfo: e.currentTarget.dataset.value,
      alarmReceiverList: list,
    })
  },

  /**
   * @name: 获取接警人列表
   * @return {*}
   */
  async getAlarmReceiverList() {
    let params = {
      orgId: this.data.form.orgId,
      userId: app.globalData.userId,
      roleName: app.globalData.rolename,
    }
    const res = await reqAlarmReceiverList(this.data.alarmPage, 20, params)
    if (res.code !== 20000) return showMsg(res.message, "error")
    let {
      rows
    } = res.data
    if (this.data.alarmPage === 1) {
      this.setData({
        alarmReceiverList: rows,
        alarmIsNextPage: true
      })
    } else if (this.data.alarmPage > 1 && rows.length) {
      this.setData({
        alarmReceiverList: this.data.alarmReceiverList.concat(rows),
        alarmIsNextPage: true
      })
    } else if (this.data.alarmPage > 1 && !rows.length) {
      showMsg('已经到底啦~')
      this.setData({
        alarmIsNextPage: false
      })
    }
    if (this.data.showPeopleCall) {
      this.clickShowPeopleCall()
    }
  },
  // 滚动到底部触发
  alarmReceiverLower() {
    if (!this.data.alarmIsNextPage) return
    this.setData({
      alarmPage: this.data.alarmPage + 1,
    })
    this.getAlarmReceiverList()
  },

  levelChange(event) {
    this.setData({
      level: event.detail,
    });
  },
  // 获取alarmReceiverArr的值
  deviceChange(event) {
    this.setData({
      alarmReceiverArr: event.detail
    })
  },
  // 点击获取alarmReceiverArr的值
  deviceToggle(event) {
    const {
      id
    } = event.currentTarget.dataset;
    this.checkboxChange(id)
  },
  // 复选框变化渲染
  checkboxChange(id) {
    const checkbox = this.selectComponent(`.checkboxes-${id}`);
    checkbox.toggle();
  },
  // 点击关闭接警人弹窗
  closePeopleCall() {
    //   清空选中的状态
    this.data.alarmReceiverList.map(item => {
      this.data.selAlarmReceiverArr.forEach(item2 => {
        if (item.id == item2.id) {
          const checkbox = this.selectComponent(`.checkboxes-${item2.id}`);
          checkbox.toggle();
        }
      })
    })



    // 取消禁用
    let list = this.data.alarmReceiverList.map(item => {
      item.disabled = false;
      return item
    })

    this.setData({
      showPeopleCall: false,
      alarmReceiverArr: [],
      alarmReceiverList: list, // 取消禁用
    })
  },
  // 确定选择接警人
  confirmPeopleCall() {
    let {
      alarmReceiverArr,
      alarmReceiverList,
    } = this.data
    const enabledReceivers = alarmReceiverList.filter(item => !item.disabled);
    const updatedReceivers = enabledReceivers.map(item => {
      const citem = alarmReceiverArr.find(citem => item.id === citem);
      if (citem !== undefined) {
        item.level = this.data.level;
        return item;
      }

      return null;
    }).filter(item => item !== null);


    const newSelAlarmReceiverArr = [...this.data.selAlarmReceiverArr, ...updatedReceivers]
      .sort((a, b) => a.level - b.level);

    this.setData({
      selAlarmReceiverArr: newSelAlarmReceiverArr
    });
    this.closePeopleCall() // 点击关闭接警人弹窗
  },
  // 去新增接警人
  goAddAlarmReceiver() {
    let {
      spaceId,
      spaceName,
      form
    } = this.data
    let info = {
      spaceId,
      spaceName,
      orgId: form.orgId
    }
    let params = JSON.stringify(info)
    wx.navigateTo({
      url: `/packageA/pages/index-inside-page/alarm-receiver-add/alarm-receiver-add?params=${params}`,
    })
  },
  // 删除某个接警人
  deleteAlarmReceiver(e) {
    const {
      id,
      value
    } = e.currentTarget.dataset;
    let {
      alarmReceiverArr,
      selAlarmReceiverArr
    } = this.data;

    alarmReceiverArr = alarmReceiverArr.filter(item => item.id !== id);
    selAlarmReceiverArr = selAlarmReceiverArr.filter(item => item.id !== id);

    this.setData({
      alarmReceiverArr,
      selAlarmReceiverArr
    });
    this.checkboxChange(id)
  },
  // 确认新增
  async confirm() {
    if (this.data.disabledBtn) return
    let {
      spaceId,
      imeiList,
      selAlarmReceiverArr,
    } = this.data
    let alarmReceiverIdList1 = []
    let alarmReceiverIdList2 = []
    let alarmReceiverIdList3 = []
    let alarmReceiverIdList4 = []
    selAlarmReceiverArr.forEach((item) => {
      switch (item.level) {
        case 1:
          alarmReceiverIdList1.push(item.id)
          break
        case 2:
          alarmReceiverIdList2.push(item.id)
          break
        case 3:
          alarmReceiverIdList3.push(item.id)
          break
        case 4:
          alarmReceiverIdList4.push(item.id)
          break
        default:
          return
      }
    })
    if (alarmReceiverIdList1.length > 6) return showMsg("一级接警人最多设置6个")
    if (alarmReceiverIdList2.length > 6) return showMsg("二级接警人最多设置6个")
    if (alarmReceiverIdList3.length > 6) return showMsg("三级接警人最多设置6个")
    if (alarmReceiverIdList4.length > 6) return showMsg("四级接警人最多设置6个")
    let arr = []
    arr = imeiList.map(item => {
      return item.imei
    })
    let imeiArr = arr.filter(Boolean) //去掉空元素项
    if (imeiArr.length <= 0) return showMsg("请输入正确的设备编码")
    if (!spaceId) return showMsg("请选择安装点")
    let params = {
      spaceId,
      alarmReceiverIdList1,
      alarmReceiverIdList2,
      alarmReceiverIdList3,
      alarmReceiverIdList4,
    }
    let params1 = {
      userId: app.globalData.userId,
      spaceId,
      imeiList: imeiArr,
    }
    await this.receiverSpaceAddFun(params)
    this.reqAddFun(params1)
  },

  // 请求接口 -- 接警人
  async receiverSpaceAddFun(params) {
    const res = await reqReceiverSpaceAdd(params)
    if (res.code != 20000) return showMsg(res.message);
  },
  // 请求接口 -- 设备
  async reqAddFun(params) {
    const res = await reqDeviceAdd(params)
    if (res.code != 20000) return showMsg(res.message);
    showMsg("安装成功", "success")
    this.setData({
      disabledBtn: true
    })
    setTimeout(() => {
      wx.navigateBack({
        delta: 1,
      })
    }, 1500)
  },

  // 单位选择弹窗打开
  onUnitSelection() {
    this.setData({
      showUnitSelection: true
    })
  },
  confirmUnitSelection(e) {
    const {
      showUnitSelection,
      orgInfo
    } = e.detail
    this.setData({
      showUnitSelection,
    })
    if (orgInfo && orgInfo.id) {

      this.setData({
        "form.orgId": orgInfo.id,
        "form.orgName": orgInfo.orgName,
        showorg: false,
        // 接警人初始状态
        alarmReceiverList: [],
        alarmIsNextPage: true,
        alarmPage: 1,
        alarmReceiverIdList1: [],
        alarmReceiverIdList2: [],
        alarmReceiverIdList3: [],
        alarmReceiverIdList4: [],
        selAlarmReceiverArr: [],
        // 安装点
        spaceName: "",
        spaceId: ""
      })
      // this.getAlarmReceiverList() //获取接警人列表
      this.getClone() //清除楼层安装点选中状态
      this.getInitBuildList() //建筑物回到最初状态
    }
  },
  // 弹出单位
  showorgClick() {
    this.setData({
      showorg: true
    })
  },
  // 关闭单位
  orgClose() {
    this.setData({
      showorg: false
    })
  },
  // 单位确认
  orgConfirm(e) {
    console.log(e);
    this.setData({
      "form.orgId": e.detail.value.id,
      "form.orgName": e.detail.value.orgName,
      showorg: false,
      // 接警人初始状态
      alarmReceiverList: [],
      alarmIsNextPage: true,
      alarmPage: 1,
      alarmReceiverIdList1: [],
      alarmReceiverIdList2: [],
      alarmReceiverIdList3: [],
      alarmReceiverIdList4: [],
      // 安装点
      spaceName: "",
      spaceId: ""
    })
    this.getAlarmReceiverList() //获取接警人列表
    this.getClone() //清除楼层安装点选中状态
    this.getInitBuildList() //建筑物回到最初状态
  },
  // 获取组织列表
  async getOrgList() {
    let params = {
      tenantId: app.globalData.tenantId,
      userId: app.globalData.userId,
      roleName: app.globalData.rolename,
    }
    const res = await reqOrgList(1, 99, params)
    if (res.code !== 20000) return showMsg(res.message)
    let {
      rows
    } = res.data
    console.log(rows);
    this.setData({
      orgList: rows
    })
  },
  // 空间id获取接警人列表
  async AlarmReceiverBySpaceId() {
    const res = await reqAlarmReceiverBySpaceId(this.data.spaceId)
    console.log(res);
    let {
      rows
    } = res.data
    if (rows && rows.length) {
      rows.sort((a, b) => a.level - b.level)
      // selAlarmReceiverArr.value = res.data.rows
      this.setData({
        selAlarmReceiverArr: rows
      })
      // showAlarmReceiver.value = ['item3']
      console.log('selAlarmReceiverArr', this.data.selAlarmReceiverArr)
    } else {
      this.setData({
        selAlarmReceiverArr: []
      })
      // showAlarmReceiver.value = []
      // alarmReceiverList.value = []
    }
  },
})